<?php

namespace App\Http\Controllers;

use App\Abc;
use App\Account;
use App\Act;
use App\Art;
use App\ArtsTransfer;
use App\Export;
use App\Import;
use App\Jobs\aaa;
use App\Refuse;
use App\SmcTransfer;
use App\Test;
use GuzzleHttp\Client;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;

class TestController extends Controller
{

    public function index()
    {
//        $list = Export::get();
////        $list = Import::get();
//        foreach ($list as $item){
//            $client = new Client(['verify' => false]);
//            $url = 'https://browser.achain.com/wallets/api/browser/act/TransactionInfo.Query?trx_id='.$item->txid;
//            $result = $client->get($url);
//            $a = json_decode($result->getBody()->getContents(),true);
//            if($a['result']['event_type']=='transfer_to_success'){
//                    $abc = new Abc();
//                    $abc->user_id = $item->user_id;
//                    $abc->txid = $item->txid;
//                    $abc->number = $item->number;
//                    $abc->save();
//            }
//        }
//        $list  = Abc::get();
//        $arr = [];
//        foreach ($list as $bbb){
//            if(!array_key_exists($bbb->user_id,$arr)){
//                $arr[$bbb->user_id] =  $bbb->number;
//            }else{
//                $arr[$bbb->user_id] +=$bbb->number;
//            }
//        }
//        dd($arr);

//        $lists = Art::get();
//        foreach ($lists as $list)
//        {
//            if(!ArtsTransfer::where('tx_id',$list->tx_id)->first()){
//                $arts = new ArtsTransfer();
//                $arts->address = $list->address;
//                $arts->tx_id = $list->tx_id;
//                $arts->num = $list->num;
//                $arts->save();
//            }
//        }


    }

    public function index1()
    {
        $list =  Import::where('user_id',142296)->get();
        $number = 0;
        foreach ($list as $item){
            $client = new Client(['verify' => false]);
            $url = 'https://browser.achain.com/wallets/api/browser/act/TransactionInfo.Query?trx_id='.$item->txid;
            $result = $client->get($url);
            $a = json_decode($result->getBody()->getContents(),true);
            if($a['result']['event_type']=='transfer_to_success'){
                $number +=$item->number;
//                    $abc = new Abc();
//                    $abc->user_id = $item->user_id;
//                    $abc->txid = $item->txid;
//                    $abc->number = $item->number;
//                    $abc->save();
            }
        }
        dd($number);
    }



    /*
     * smcRequest  通用请求方法
     * $method   string   方法名
     *
     * */
    public function smcRequest($method, $params)
    {
        $client     = new Client();
        $url        = 'http://39.104.66.195:8299/rpc';
        $loginField = base64_encode("user:password");
        $params     = [
            'headers' => [
                'Content-Type' => 'application/json',
                'Authorization' => '000000' . $loginField,
            ],
            'json' => [
                'id' => 1,
                'method' => $method,
                'params' => $params,
            ],
        ];
        try {
            $response = $client->request('POST', $url, $params);
        } catch (\Exception $exception) {
            \Log::debug($exception->getMessage());
            return 2;
        }
        $content = $response->getBody()->getContents();
        return json_decode($content, true);
    }


    /*
     * 扫描区块
     * return $arr  返回SMC的交易哈希及数量
     * */
    public function Blockcycle()
    {
//        $startBlock = Redis::get('startSmcBlock') ? Redis::get('startSmcBlock') : 1337559;
        $startBlock = \Cache::get('start_SmcBlock', '1337559');
        $endBlock   = $this->smcRequest('blockchain_get_block_count', [])['result'];
        $arr        = [];
        for ($i = $startBlock; $startBlock < $endBlock; $i++) {
            $result = $this->smcRequest('blockchain_get_block', [$i]);//获取最新区块的交易
            if (!empty($result['result']['user_transaction_ids'])) {
                foreach ($result['result']['user_transaction_ids'] as $result_trx_id) {
                    $client = new Client(['verify'=>false]);
                    $check_contract = $client->get('https://browser.achain.com/wallets/api/browser/act/Query.Type?keyword='.$result_trx_id)->getBody()->getContents();
                    $check_contract = json_decode($check_contract,true);
                    if($check_contract['result']['record_num']==1) continue;


                    $contract_result = $this->smcRequest('blockchain_get_pretty_contract_transaction', [$result_trx_id]);//通过交易哈希  查询合约交易
                    if ($contract_result !== 2) {
                        if ($contract_result['result']['to_contract_ledger_entry']['to_account'] == 'CON2W6PbuBrGcB3EGFTK81sDfJmrMUTyXqta') {//判断是不是SMC合约交易
                            $is_confirm = $this->smcRequest('blockchain_get_pretty_transaction', [$contract_result['result']['orig_trx_id']]);
                            if ($is_confirm['result']['is_confirmed'] == true) {//判断是否确认
                                //查询地址余额
                                $balance = $this->smcRequest('blockchain_get_events',[$i,$result_trx_id]);
                                if(!empty($balance['result'])){
                                    if($balance['result'][0]['event_type']=='transfer_to_success'){
                                        $array_address = explode('|', $contract_result['result']['reserved'][1]);
                                        if (strlen($array_address[0]) > 60) {
                                            if(!Db::table('smc_transfers')->where('tx_id',$contract_result['result']['orig_trx_id'])->first()){
                                                DB::table('smc_transfers')->insert([
                                                    'tx_id' => $contract_result['result']['orig_trx_id'],
                                                    'address' => $array_address[0],
                                                    'num' => $array_address[1]
                                                ]);
                                                \Cache::forever('start_SmcBlock', $i);
                                            }
                                        }
                                    }
                                };
                            }
                        }
                    }
                }
            }
        }
    }

    /*
     * 返回交易信息
     * */
    public function SmcRecord($address)
    {
        $res = DB::table('smc_transfers')->where('address', $address)->get();
        return response()->json($res);
    }


    /*
     * arts  请求方法
     * */
    public function artsRequest($method, $params)
    {
        $client     = new Client();
        $url        = 'http://47.95.123.33:8299/rpc';
        $loginField = base64_encode("user:password");
        $params     = [
            'headers' => [
                'Content-Type' => 'application/json',
                'Authorization' => '000000' . $loginField,
            ],
            'json' => [
                'id' => 1,
                'method' => $method,
                'params' => $params,
            ],
        ];
        try {
            $response = $client->request('POST', $url, $params);
        } catch (\Exception $exception) {
            return 2;
        }
        $content = $response->getBody()->getContents();
        return json_decode($content, true);
    }


    /*
     * 扫描区块
     * return $arr  返回ARTS的交易哈希及数量
     * */
    public function BlockcycleArts()
    {
        $startBlock = Redis::get('startArtsBlock') ? Redis::get('startArtsBlock') : 1890268;
//        $startBlock = \Cache::get('start_ArtsBlock', '1890268');
        $endBlock   = $this->artsRequest('blockchain_get_block_count', [])['result'];
        for ($i = $startBlock; $endBlock > $i; $i++){
            $result = $this->artsRequest('blockchain_get_block', [$i]);//获取最新区块的交易
            if (!empty($result['result']['user_transaction_ids'])) {
                foreach ($result['result']['user_transaction_ids'] as $result_trx_id) {
                    $contract_result = $this->artsRequest('blockchain_get_pretty_contract_transaction', [$result_trx_id]);//通过交易哈希  查询合约交易
                    if ($contract_result !== 2) {
                        if ($contract_result['result']['to_contract_ledger_entry']['to_account'] == 'CON73xk16ETk4YTBRztyvXgu3cTVYKd6eZc1') {//判断是不是ARTS合约交易
                            $is_confirm = $this->artsRequest('blockchain_get_pretty_transaction', [$contract_result['result']['orig_trx_id']]);
                            if ($is_confirm['result']['is_confirmed'] == true) {//判断是否确认
                                //查询地址余额
                                $balance = $this->artsRequest('blockchain_get_events',[$i,$result_trx_id]);
                                if(!empty($balance['result'])){
                                    if($balance['result'][0]['event_type']=='transfer_to_success'){
                                        $array_address = explode('|', $contract_result['result']['reserved'][1]);
                                        if (strlen($array_address[0]) > 60) {
                                            if(!ArtsTransfer::where('tx_id',$contract_result['result']['orig_trx_id'])->first()) {
                                                $arts = new ArtsTransfer();
                                                $arts->tx_id = $contract_result['result']['orig_trx_id'];
                                                $arts->address = $array_address[0];
                                                $arts->num = $array_address[1];
                                                $arts->save();
//                                            if(!Db::table('arts_transfers')->where('tx_id',$contract_result['result']['orig_trx_id'])->first()){
//                                                DB::table('arts_transfers')->insert([
//                                                    'tx_id' => $contract_result['result']['orig_trx_id'],
//                                                    'address' => $array_address[0],
//                                                    'num' => $array_address[1]
//                                                ]);
//                                                \Cache::forever('start_ArtsBlock', $i);
                                                Redis::set('startArtsBlock', $i);
                                            }
                                        }
                                    }
                                };
                            }
                        }
                    }
                }
            }
        }
    }

    //循环每个区块 监控可疑账号
    public function cycle()
    {
        $startBlock =  Redis::get('startRefuseBlock') ? Redis::get('startRefuseBlock') : 1719663;
        $endBlock = $this->artsRequest('blockchain_get_block_count', [])['result'];
        while ($startBlock<$endBlock){
            $result = $this->artsRequest('blockchain_get_block', [$startBlock]);//获取最新区块的交易
            if(!empty($result['result']['user_transaction_ids'])){
                //判断是不是合约币
                $client = new Client(['verify'=>false]);
                foreach ($result['result']['user_transaction_ids'] as $transaction_id){
                    $check_contract = $client->get('https://browser.achain.com/wallets/api/browser/act/Query.Type?keyword='.$transaction_id)->getBody()->getContents();
                    $check_contract = json_decode($check_contract,true);
                    if($check_contract['result']['record_num']==1) continue;
                    $contract_result = $this->artsRequest('blockchain_get_pretty_contract_transaction', [$transaction_id]);//通过交易哈希  查询合约交易
                    $transfer_address = Refuse::pluck('transfer_address')->toArray();
                    $accept_address = Refuse::pluck('accept_address')->toArray();
                    $check_address = array_unique(array_merge($transfer_address,$accept_address));
                    if(in_array($contract_result['result']['to_contract_ledger_entry']['from_account'],$check_address)&&$contract_result['result']['to_contract_ledger_entry']['to_account']=='CON73xk16ETk4YTBRztyvXgu3cTVYKd6eZc1'){
                        $refuse_address =  explode('|', $contract_result['result']['reserved'][1]);
                        if(Refuse::where('transfer_address',$refuse_address[0])->first()) continue;
                        if(Refuse::where('tx_id',$contract_result['result']['orig_trx_id'])->first()) continue;
                        $refuse = new Refuse();
                        $refuse->accept_address = $refuse_address[0];
                        $refuse->transfer_address = $contract_result['result']['to_contract_ledger_entry']['from_account'];
                        $refuse->tx_id = $contract_result['result']['orig_trx_id'];
                        $refuse->num = $refuse_address[1];
                        $refuse->save();
                    }
                }
            }
            $startBlock++;
        }
        Redis::set('startRefuseBlock',$endBlock);
    }

    //扫描act
    public function getActblock()
    {
        $act_pid = \Cache::get('act_pid');
        if($act_pid) return;
        \Cache::forever('act_pid',1);
        $startBlock = \Cache::get('act_startBlock', '1606154');
        $endBlock   = $this->smcRequest('blockchain_get_block_count', [])['result'];
        while ($startBlock <= $endBlock) {
            $result               = $this->smcRequest('blockchain_get_block', [$startBlock]);//获取最新区块的交易
            $user_transaction_ids = $result['result']['user_transaction_ids'];
            if (!empty($user_transaction_ids)) {
                foreach ($user_transaction_ids as $user_transaction_id) {
                    //判断hash是否已经存在
                    if (Act::where('tx_id', $user_transaction_id)->first()) continue;

                    $act_result = $this->smcRequest('blockchain_get_pretty_transaction', [$user_transaction_id]);
                    //判断交易是否确认
                    if (!$act_result['result']['is_confirmed']) continue;
                    //获取子地址
                    $son_result  = $this->smcRequest('blockchain_get_transaction', [$user_transaction_id]);
                    $son_account = $son_result['result'][1]['trx']['alp_account'];
                    //判断是不是我们的子地址交易
                    if (strpos($son_account, 'ACTHVcmzjEchucTDNsXwQ5TVXi7zay6BTakv') === false) continue;
                    $amount       = $act_result['result']['ledger_entries'][0]['amount'];
                    $amount       = $amount['amount'] / 100000;
                    $act          = new Act();
                    $act->address = $son_account;
                    $act->tx_id   = $user_transaction_id;
                    $act->num     = $amount;
                    $act->block   = $startBlock;
                    if (!$act->save()) {
                        \Log::debug($user_transaction_id . '保存记录失败');
                    }
                }
            }
            $startBlock++;
            \Cache::forever('act_startBlock', $startBlock);
        }
        \Cache::forever('act_pid',0);
    }


    /*
    * 返回交易信息
    * */
    public function ArtsRecord($address)
    {
        $res = DB::table('arts_transfers')->where('address', $address)->get();
        return response()->json($res);
    }

    /*
    * 返回交易信息
    * */
    public function ActRecord($address)
    {
        $res = Act::where('address', $address)->get();
        return response()->json($res);
    }
}
